import {
  Button,
  Card,
  Popconfirm,
  Form,
  Input,
  Space,
  Layout,
  message,
  Upload,
  DatePicker,
  Row,
  Col,
  Switch,
  Modal,
  Radio,
} from 'antd';
import Table, { ColumnsType } from 'antd/es/table';
import { isNil } from 'ramda';
import { useState, useEffect, useRef } from 'react';
import { useTranslation } from 'react-i18next';
import dayjs from 'dayjs';
import { LoadingOutlined, PlusOutlined, DeleteOutlined } from '@ant-design/icons';
import { IconButton, Iconify, SvgIcon } from '@/components/icon';
import { useUserPermission } from '@/store/userStore';
import ProTag from '@/theme/antd/components/tag';

import PermissionModal, { type PermissionModalProps } from './permission-modal';
import Back from '@/components/router/Back';

import { Tabs } from 'antd';
import type { TabsProps, GetProp, UploadProps } from 'antd';

import { useRouter, useParams } from '@/router/hooks';
import appService from '@/api/services/appService';

import useWindowWidth from '@/hooks/event/use-window-width';
import RouterMenu from '../components/menus/RouterMenu';
import { useManagePage, useConfigActions, useInitializeData } from '@/store/configStore';

import { BrandingEnum, LicenseEditionEnum, industryOptions } from '@/common';
import JoyrideGuide from '@/pages/components/joyride-guide';
import './style/index.css';

import LogoIcon from '@/assets/icons/ai-logo-eai.svg';

import { useSize } from 'ahooks';
import { generateUUID } from '@/utils/common';

const { Header } = Layout;

export interface Permission {
  id: string;
  key: string;
  content: string;
  answer?: string;
  enable?: boolean;
  order?: number;
  row?: number;
}

const defaultPermissionValue: Permission = {
  id: new Date().toDateString(),
  key: new Date().toDateString(),
  content: '',
  answer: '',
  order: 1,
  enable: true,
  row: -1,
};

const defaultBaseValue: any = {};

interface FormBaseValue {
  [key: string]: any;
}

export default function PermissionPage() {
  const { id } = useParams();
  const { isPc } = useWindowWidth();
  const [permissions, setPermissions] = useState([]);

  const [formBase] = Form.useForm();
  const [formBaseValue, setFormBaseValue] = useState<FormBaseValue>({});
  const managePage = useManagePage();

  const [loading, setLoading] = useState(false);
  const [imageUrl, setImageUrl] = useState<string>();
  const [logoPath, setLogoPath] = useState<string>();
  const [showDeleteButton, setShowDeleteButton] = useState(false);

  const [showtip, setShowtip] = useState(true);

  const { fetchAppInfo } = useConfigActions();
  const ref = useRef<HTMLDivElement>(null);
  const size = useSize(ref);

  const initializeData = useInitializeData()
  const isExtensionsDisabled = initializeData?.license_edition === LicenseEditionEnum.basic;

  useEffect(() => {
    id &&
      appService
        .brandingDetail(id, 'console')
        .then((res) => {
          setFormBaseValue(res);
          setPermissions(res?.hot_issues);
          if (res.logo) {
            setImageUrl(res?.logo);
          } else {
            setImageUrl(LogoIcon);
          }
          // setShowtip(res?.enable_extensions_recommend);
          if (res?.release_time) {
            const releaseTime = dayjs(res.release_time);
            formBase.setFieldsValue({
              ...res,
              release_time: releaseTime, // 使用 dayjs 对象
            });
            setFormBaseValue({ ...res, release_time: releaseTime });
          } else {
            formBase.setFieldsValue({ ...res });
          }
        })
        .catch((error) => {
          console.log(error);
        });
  }, []);

  const router = useRouter();

  const [activeKey, setActiveKey] = useState('1');

  const saveAppInfo = async () => {
    appService.updateBranding(id, formBase.getFieldsValue()).then(() => {
      setFormBaseValue(formBase.getFieldsValue());
      id && fetchAppInfo(id);
      message.success('保存成功');
    });
  };

  const resetAppInfo = async () => {
    formBase.setFieldsValue({ ...formBaseValue });
    if (formBaseValue.logo) {
      setImageUrl(formBaseValue?.logo);
    } else {
      setImageUrl(LogoIcon);
    }
  };

  const validateTabChange = async (nextTab?: string) => {
    const handleTabChange = () => {
      if (nextTab) {
        setActiveKey(nextTab);
      } else {
        router.push(managePage);
      }
    };

    if (activeKey !== '1') {
      handleTabChange();
      return;
    }

    const formData = formBase.getFieldsValue();
    const formKeys = Object.keys(formData);
    const isEqual = !formKeys.some((key) => formData[key] !== formBaseValue?.[key]);

    if (isEqual) {
      handleTabChange();
      return;
    }

    Modal.confirm({
      title: '确认保存',
      content: '配置信息未保存，确定保存吗？',
      okText: '确定',
      cancelText: '取消',
      cancelButtonProps: {
        className: 'custom-cancel-button',
      },
      okButtonProps: {
        style: {
          backgroundColor: '#6640FF',
          borderColor: '#6640FF'
        }
      },
      onOk: async () => {
        await saveAppInfo();
        handleTabChange();
      },
      onCancel: () => {
        resetAppInfo();
        handleTabChange();
      },
    });
  };

  const onChange = (newActiveKey: string) => {
    validateTabChange(newActiveKey);
  };

  const [permissionModalProps, setPermissionModalProps] = useState({
    formValue: { ...defaultPermissionValue },
    title: '新建',
    show: false,
    onOk: (value: Permission, row: number) => {
      console.log(row);
      setPermissions((prev: any) => {
        console.log(prev);
        message.success('更新成功');
        if (row >= 0) {
          prev[row] = value;
          appService
            .updateBranding(id, {
              hot_issues: prev,
            })
            .then(() => {
              id && fetchAppInfo(id);
            });
          return prev;
        } else {
          appService
            .updateBranding(id, {
              hot_issues: [...prev, value],
            })
            .then(() => {
              id && fetchAppInfo(id);
            });
          return [...prev, value];
        }
      });
      setPermissionModalProps((prev) => ({ ...prev, show: false }));
    },
    onCancel: () => {
      setPermissionModalProps((prev) => ({ ...prev, show: false }));
    },
  });

  const columns: ColumnsType<Permission> = [
    {
      title: '内容',
      dataIndex: 'content',
      width: 300,
      render: (_, record) => <div>{record.content}</div>,
    },
    {
      title: '回答',
      dataIndex: 'answer',
      width: 300,
      render: (_, record) => <div>{record.answer}</div>,
    },
    {
      title: '状态',
      dataIndex: 'enable',
      align: 'center',
      width: 120,
      render: (enable) => (
        <ProTag color={enable === false ? '#6E35FF' : '#6E35FF'}>
          {enable === false ? '隐藏' : '展示'}
        </ProTag>
      ),
    },
    { title: '排序', dataIndex: 'order', width: 60 },

    {
      title: '操作',
      key: 'operation',
      align: 'center',
      width: 100,
      render: (_, record, index) => (
        <div className="flex w-full justify-center text-gray">
          <IconButton onClick={() => onEdit(record, index)}>
            <SvgIcon icon="tdesign--edit-2" style={{ fontSize: '15px' }} />
          </IconButton>
          <Popconfirm
            title="删除该记录"
            okText="Yes"
            cancelText="No"
            placement="left"
            onConfirm={() => onDelete(record, index)}
          >
            <IconButton>
              <SvgIcon icon="tdesign--delete-v2" style={{ fontSize: '15px' }} />
            </IconButton>
          </Popconfirm>
        </div>
      ),
    },
  ];

  const columns2: ColumnsType<Permission> = [
    {
      title: '内容',
      dataIndex: 'content',
      key: generateUUID(),
      render: (_, record) => (
        <div>
          <div
            key={Math.random().toString(36)}
            style={{
              maxWidth: size?.width ? `${size.width - 100}px` : '250px',
              overflow: 'hidden',
              textOverflow: 'ellipsis',
              whiteSpace: 'nowrap',
            }}
          >
            {record.content}
          </div>
          {/* <div
            title="record.answer"
            style={{
              maxWidth: size?.width ? `${size.width - 100}px` : '250px',
              overflow: 'hidden',
              whiteSpace: 'nowrap',
              textOverflow: 'Ellipsis',
              color: 'grey',
            }}
          >
            {record.answer}
          </div> */}
        </div>
      ),
    },

    {
      title: '操作',
      key: 'operation',
      align: 'center',
      width: 80,
      render: (_, record, index) => (
        <div className="flex w-full justify-center text-gray">
          <IconButton onClick={() => onEdit(record, index)}>
            <SvgIcon icon="tdesign--edit-2" style={{ fontSize: '15px' }} />
          </IconButton>
          <Popconfirm
            title="删除该记录"
            okText="Yes"
            cancelText="No"
            placement="left"
            onConfirm={() => onDelete(record, index)}
          >
            <IconButton>
              <SvgIcon icon="tdesign--delete-v2" style={{ fontSize: '15px' }} />
            </IconButton>
          </Popconfirm>
        </div>
      ),
    },
  ];

  const onDelete = (record: Permission, index: number) => {
    setPermissions((prev) => {
      const updatedPermissions = prev.filter((_, i) => i !== index);
      appService
        .updateBranding(id, {
          hot_issues: updatedPermissions,
        })
        .then(() => {
          id && fetchAppInfo(id);
        });
      message.success('删除成功');
      return updatedPermissions;
    });
  };

  const onCreate = () => {
    setPermissionModalProps((prev) => ({
      ...prev,
      show: true,
      ...defaultPermissionValue,
      title: '新建热门问题',
      row: -1,
      formValue: { ...defaultPermissionValue },
    }));
  };

  const onEdit = (formValue: Permission, index: number) => {
    console.log('formValue============', formValue, index);
    setPermissionModalProps((prev) => ({
      ...prev,
      show: true,
      title: '编辑',
      row: index,
      formValue,
    }));
  };

  const customRequest = async (option: any) => {
    const { onProgress, onError, onSuccess, file, action } = option;

    // 确保 file 是 File 或 Blob 对象
    if (!(file instanceof File || file instanceof Blob)) {
      return;
    }

    try {
      const fileType = file.type.split('/')[1];
      const fileName = `logo.${fileType}`;
      const data = await appService.postFcsUploadImage({
        file_name: fileName,
        file: file,
      });
      // 设置 logoPath 并等待状态更新完成
      await new Promise((resolve) => {
        setLogoPath(data);
        setTimeout(resolve, 0); // 确保状态更新完成
      });
      onSuccess('ok', file);
    } catch (error) {
      // 处理错误并通知 Upload 组件上传失败
      console.error('Upload failed:', error);
      onError({ error });
    }
  };

  const handleChange: UploadProps['onChange'] = ({ file }) => {
    console.log(file, file.status);

    if (file.status === 'uploading') {
      setLoading(true);
      return;
    }
    if (file.status === 'done') {
      // Get this url from response in real world.
      getBase64(file.originFileObj as FileType, (url) => {
        setLoading(false);
        setImageUrl(url);
      });
      console.log('完成上传', logoPath);
      formBase.setFieldValue('logo', logoPath);
      // return logoPath
    } else {
      formBase.setFieldValue('logo', '');
    }
  };

  const getBase64 = (img: FileType, callback: (url: string) => void) => {
    const reader = new FileReader();
    reader.addEventListener('load', () => callback(reader.result as string));
    reader.readAsDataURL(img);
  };

  // const beforeUpload = (file: FileType) => {
  //   const isLt100K = file.size / 1024 < 100; // Corrected the size check to be less than 100KB
  //   if (!isLt100K) {
  //     message.error('Image must be smaller than 100KB!');
  //     return false;
  //   }

  //   return isLt100K;

  // };

  const beforeUpload = (file: FileType) => {
    // 检查文件大小是否小于100KB
    const isLt100K = file.size / 1024 < 100;
    if (!isLt100K) {
      // message.error('Image must be smaller than 100KB!');
      message.error('图片大小超出100KB！');
      console.log('aaaa');
      formBase.setFieldValue('logo', '');
      return false;
    }
    // 创建一个Promise来处理异步加载图像的过程
    const imageAspectRatioCheck = new Promise((resolve, reject) => {
      const img = new Image();
      img.src = URL.createObjectURL(file);
      img.onload = () => {
        const aspectRatio = img.width / img.height;
        const isValidAspectRatio = aspectRatio >= 0.8 && aspectRatio <= 1.2;

        console.log('aspectRatio===============', aspectRatio);

        if (!isValidAspectRatio) {
          setTimeout(() => {
            // setImageUrl(formBaseValue.logo);
            // message.error('Image aspect ratio must be between 0.8 and 1.2!');
            message.error('图片宽高比必须在0.8到1.2之间！');
          }, 500);
          formBase.setFieldValue('logo', '');
          resolve(false);
        } else {
          resolve(true);
        }
        URL.revokeObjectURL(img.src); // 清除URL对象以释放内存
      };
      img.onerror = () => {
        formBase.setFieldValue('logo', '');
        message.error('图像上传失败');
        resolve(false);
      };
    });

    return imageAspectRatioCheck.then((isValid) => isValid && isLt100K);
  };

  const uploadButton = (
    <button style={{ border: 0, background: 'none' }} type="button">
      {loading ? <LoadingOutlined /> : <PlusOutlined />}
      {/* <div style={{ marginTop: 8 }}>Upload</div> */}
    </button>
  );

  const handleRemoveImage = () => {
    formBase.setFieldValue('logo', '');
    setImageUrl('');
    setShowDeleteButton(false);
  };

  const handleMouseEnter = () => setShowDeleteButton(true);
  const handleMouseLeave = () => setShowDeleteButton(false);

  const normFile = (e: any) => {
    // customRequest(e.file)
    // console.log("eeeeeeeeeeeee",e,logoPath);
    return logoPath;
  };

  const items: TabsProps['items'] = [
    {
      key: '1',
      label: '应用基础信息',
      icon: (
        <SvgIcon
          icon="mdi--application-cog-outline"
          size={18}
          style={{ padding: '0 0 3px 0', alignItems: 'center' }}
        ></SvgIcon>
      ),
      children: (
        <div
          style={{
            width: '100%',
            padding: isPc ? '0 30% 0 4%' : '0px',
            float: 'left',
            position: 'relative',
          }}
        >
          <div
            style={{
              // position: isPc ? 'absolute' : 'unset',
              top: '-64px',
              right: '0px',
              display: 'flex',
              justifyContent: 'flex-end',
              marginBottom: '10px',
            }}
          >
            <Space>
              <Button icon={<SvgIcon icon="ri--reset-left-fill"></SvgIcon>} onClick={resetAppInfo}>
                重置
              </Button>
              <Button
                className="jr-step-7"
                type="primary"
                icon={<SvgIcon icon="icon-park-outline--save-one"></SvgIcon>}
                onClick={saveAppInfo}
              >
                保存
              </Button>
            </Space>
          </div>

          <Form
            initialValues={formBaseValue}
            form={formBase}
            // labelsCol={{ span: 4 }}
            wrapperCol={{ span: 24 }}
            layout="vertical"
          >
            {
              !isExtensionsDisabled &&
              <Form.Item
                layout="horizontal"
                label="应用导航"
                className="ant-col-text"
                colon={false}
                name="enable_extensions_recommend"
                rules={[{ required: true }]}
                style={{ marginBottom: '0px' }}
              >
                <Switch checkedChildren="开启" unCheckedChildren="关闭" />
              </Form.Item>
            }
            {!isExtensionsDisabled && showtip && (
              <p
                style={{
                  // border: '1px solid blue',
                  borderRadius: '8px',
                  padding: '4px 8px',
                  color: 'grey',
                  // backgroundColor: '#EDEAF3',
                }}
              >
                {'开启应用导航功能后，对话中将智能推荐并提供相关应用或资源的访问链接'}
              </p>
            )}
            <Form.Item
              className="jr-step-6"
              label="应用名称"
              name="display_name"
              style={{ marginTop: '24px' }}
              rules={[{ required: true, message: '请输入内容' }]}
            >
              <Input
                style={{ borderRadius: '6px', border: '1px solid #DBDBDC' }}
                placeholder={BrandingEnum.display_name}
              />
            </Form.Item>
            <Form.Item label="首页介绍语" name="home_text">
              <Input.TextArea
                placeholder={BrandingEnum.home_text}
                style={{ borderRadius: '6px', border: '1px solid #DBDBDC' }}
              />
            </Form.Item>
            <Form.Item label="功能中心介绍语" name="management_text">
              <Input.TextArea
                placeholder={BrandingEnum.management_text}
                style={{ borderRadius: '6px', border: '1px solid #DBDBDC' }}
              />
            </Form.Item>
            <Form.Item label="对话开场白" name="welcome_text">
              <Input.TextArea
                placeholder={BrandingEnum.welcome_text}
                style={{ borderRadius: '6px', border: '1px solid #DBDBDC' }}
              />
            </Form.Item>

            <Form.Item label="应用场景" name="industry_type">
              <Radio.Group>
                {industryOptions.map((option) => (
                  <Radio key={option.value} value={option.value}>
                    {option.label}
                  </Radio>
                ))}
              </Radio.Group>
            </Form.Item>

            <Form.Item label="组织名称" name="organization_name">
              <Input
                placeholder="请填写组织名称"
                style={{ borderRadius: '6px', border: '1px solid #DBDBDC' }}
              />
            </Form.Item>
            <Form.Item label="上线日期" name="release_time">
              <DatePicker
                style={{ width: '100%', borderRadius: '6px', border: '1px solid #DBDBDC' }}
                placeholder="请选择应用上线日期"
              />
            </Form.Item>
            {/* <Row gutter={16}>
              <Col span={12}>
                <Form.Item
                  label="学校名称"
                  name="organization_name"
                  rules={[{ required: true, message: '请输入内容' }]}
                >
                  <Input />
                </Form.Item>
              </Col>
              <Col span={12}>
                <Form.Item
                  label="上线日期"
                  name="release_time"
                  rules={[{ required: true, message: '请输入内容' }]}
                >
                  <DatePicker style={{ width: '100%' }} />
                </Form.Item>
              </Col>
            </Row> */}
            <Form.Item label="应用LOGO" name="logo">
              <Upload
                name="image_upload"
                listType="picture-card"
                className="avatar-uploader ant-upload-box"
                showUploadList={false}
                customRequest={customRequest}
                beforeUpload={beforeUpload}
                onChange={handleChange}
              >
                {imageUrl ? (
                  <div
                    style={{
                      position: 'relative',
                      overflow: 'hidden',
                      width: '100px',
                      height: '100px',
                      borderRadius: '6px',
                    }}
                    onMouseEnter={handleMouseEnter}
                    onMouseLeave={handleMouseLeave}
                  >
                    <img
                      src={imageUrl}
                      alt="avatar"
                      style={{ width: '100%', objectFit: 'cover' }}
                    />
                    {showDeleteButton && (
                      <div
                        style={{
                          position: 'absolute',
                          top: -5,
                          right: -1,
                          zIndex: 100,
                          backgroundColor: 'rgba(0,0,0,0.5)',
                          color: 'rgba(0,0,0,0.5)',
                          width: '105px',
                          height: '105px',
                          borderRadius: '6px',
                          display: 'flex',
                          justifyContent: 'center',
                          alignItems: 'center',
                        }}
                        onClick={(event) => {
                          event.stopPropagation();
                          handleRemoveImage();
                        }}
                      >
                        <IconButton>
                          <SvgIcon
                            icon="ic-delete"
                            style={{ fontSize: '25px', color: '#ffffff' }}
                          />
                        </IconButton>
                      </div>
                    )}
                  </div>
                ) : (
                  uploadButton
                )}
              </Upload>
            </Form.Item>
          </Form>
        </div>
      ),
    },
    {
      key: '2',
      label: '热门问题',
      icon: (
        <SvgIcon
          icon="mdi--chat-question"
          size={18}
          style={{ padding: '0 0 3px 0', alignItems: 'center' }}
        ></SvgIcon>
      ),
      children: (
        <Card
          // title="热门问题"
          // extra={
          //   <Button
          //     type="primary"
          //     icon={<SvgIcon size={16} icon="ri--add-fill"></SvgIcon>}
          //     onClick={() => onCreate()}
          //   >
          //     新建
          //   </Button>
          // }
          ref={ref}
          style={{ border: 'none', backgroundColor: '#F4F7FB' }}
          className="card-head card-body relative"
        >
          <div className="flex items-center justify-between">
            <div
              style={{
                fontSize: '12px',
                borderRadius: '8px',
                padding: '4px 8px',
                color: '#6E35FF',
                backgroundColor: '#EDEAF3',
              }}
            >
              仅展示前5条记录
            </div>
            <div>
              <Button
                // size="small"
                type="primary"
                icon={<SvgIcon size={16} icon="ri--add-fill"></SvgIcon>}
                onClick={() => onCreate()}
              >
                新建
              </Button>
            </div>
          </div>

          <Table
            rowKey="content"
            size="small"
            scroll={{ x: 'max-content' }}
            pagination={false}
            columns={isPc ? columns : columns2}
            dataSource={permissions}
            className="ant-table-css"
          />

          <PermissionModal {...permissionModalProps} />
        </Card>
      ),
    },
  ];

  return (
    <>
      <Layout className="h-full" style={{ background: '#ECEFF8' }}>
        <Header style={{ background: '#FBFCFF', padding: 0, borderBottom: '1px solid #DDE5FF' }}>
          <div className="flex flex-nowrap items-center ">
            <div>
              <Back
                title={`返回`}
                onClick={() => {
                  validateTabChange();
                }}
              />
            </div>
            {/* <div
              style={{
                width: '1px',
                height: '16px',
                border: '1px solid black',
                margin: '0 25px',
              }}
            ></div>

            <div style={{ display: 'flex', alignItems: 'center' }}>
              <SvgIcon
                icon="ri--apps-3-fill"
                style={{ marginRight: '15px', color: '#E88C27', fontSize: '20px' }}
              ></SvgIcon>
              <div style={{
                fontWeight: 400,
                fontSize: '16px',
                color: '#6C7180'
              }}>
                应用管理
              </div>
            </div>
            <div
              style={{
                width: '2px',
                height: '20px',
                backgroundColor: '#8b8282',
                marginLeft: '20px',
              }}
            />
            <RouterMenu /> */}
          </div>
        </Header>

        <div
          style={{
            padding: isPc ? '10px' : '10px',
            overflow: 'auto',
          }}
        >
          <div
            style={{
              // border: '1px solid red',
              padding: '10px',
              backgroundColor: '#F4F7FB',
              borderRadius: '8px',
            }}
          >
            <Tabs activeKey={activeKey} items={items} onChange={onChange} />
          </div>
        </div>
        <JoyrideGuide />
      </Layout>
    </>
  );
}
